﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GoogleNewsReader.Extraction
{
    public class SimpleCommentDetectorProvider : CommentDetectorProvider
    {
        public override List<Statistics> Detect(CommentDetectorOptions options)
        {
            Dictionary<string, int> cssClassRedundancy = new Dictionary<string, int>();
            foreach (var statistics in options.Source)
            {
                if (statistics.ParentNode == null)
                    continue;

                string cssClass = "";
                var classAttribute = statistics.ParentNode.Attributes["class"];
                if (classAttribute != null)
                {
                    cssClass = classAttribute.Value;
                }

                if (!cssClassRedundancy.ContainsKey(cssClass))
                {
                    cssClassRedundancy.Add(cssClass, 1);
                }
                else
                {
                    cssClassRedundancy[cssClass]++;
                }
            }

            KeyValuePair<string, int> element = new KeyValuePair<string, int>();
            foreach (var pair in cssClassRedundancy)
            {
                if (pair.Value > element.Value)
                {
                    element = pair;
                }
            }

            if (element.Value < 3) // there must be three comments at least to be considered
            {
                return new List<Statistics>();
            }
            string mostRepeatedCssClass = element.Key;
            List<Statistics> comments = new List<Statistics>();

            for (int i = 0; i < options.Source.Count; i++)
            {
                var pair = options.Source[i];
                if (pair.ParentNode == null)
                    continue;

              

                var classAttribute = pair.ParentNode.Attributes["class"];
                if (classAttribute == null)
                {
                    continue;
                }

                if (classAttribute.Value == mostRepeatedCssClass)
                {
                    comments.Add(pair);
                    options.Source.RemoveAt(i);
                    i--;
                }
            }

            return comments;
        }
    }
}
